/**
 * Created by 55456 on 2016/4/8.
 */
/*
* 目的：封装的一个工具集，含有register，login，auth三个模块，使用redis数据库面向开发者。
* 开发者可以自己控制注册的表段，登录的表段，验证的appId和token
* todo:修改attr变成appId验证封装成三个模块
* */
var crypto = require("crypto");
var Base = function Base(attr){
    this.attr = arguments[0];
};

//主动调用检查权限
Base.prototype.CheckAttr = function(){
    //todo:User extend attr
    var ctx = arguments[0];
    if(!ctx){
        throw("route controller need context");
    }
    if(this.attr === "public"){
        return true;
    }else if(!this.attr || this.attr === "private"){
        return this._CheckPermission(ctx);
    }else{
        throw("Do not support this kind of route controller");
    }
};

Base.prototype._CheckPermission = function (ctx){
    return ctx.currentUser;
    //todo:bind errors
    //this.errors = "my errors";
    // if(ctx.user){
    //     return true;
    // }else{
    //     return false;
    // }
};

Base.prototype._parseWhereArgs = function (args){
    var newArgs = [];
    Object.keys(args).forEach(function(idx,index){
        if(index !== 1 && index !== 0){
            newArgs.push(args[idx]);
        }
    });
    return this._extend.apply(this,newArgs);
};


Base.prototype._extend = function(obj, extObj) {
    if (arguments.length > 2) {
        for (var a = 1; a < arguments.length; a++) {
            this._extend(obj, arguments[a]);
        }
    } else {
        for (var i in extObj) {
            obj[i] = extObj[i];
        }
    }
    return obj;
};


Base.prototype.md5 = function (str, encoding) {
    encoding = encoding || 'base64';
    var md5 = crypto.createHash('md5');
    md5.update(str);
    return md5.digest(encoding);
};

module.exports = Base;